<template>
  <div class="pan-statistics-report">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <el-button type="primary" @click="handleExportReport">
        导出报表
      </el-button>
    </div>

    <!-- 时间筛选区域 -->
    <el-card class="filter-card" :body-style="{ padding: '15px' }">
      <div class="filter-container">
        <div class="filter-item">
          <span class="filter-label">时间范围:</span>
          <el-select
            v-model="timeRange"
            placeholder="请选择时间范围"
            size="default"
            @change="handleTimeRangeChange"
          >
            <el-option label="今日" value="today" />
            <el-option label="昨日" value="yesterday" />
            <el-option label="本周" value="week" />
            <el-option label="本月" value="month" />
            <el-option label="上月" value="lastMonth" />
            <el-option label="近30天" value="30d" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </div>

        <div class="filter-item" v-if="timeRange === 'custom'">
          <span class="filter-label">自定义:</span>
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            size="default"
          />
        </div>

        <div class="filter-actions">
          <el-button @click="refreshData"> 刷新 </el-button>
          <el-button @click="toggleComparison"> 对比 </el-button>
        </div>
      </div>
    </el-card>

    <!-- 核心指标区域 -->
    <el-card class="metrics-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">核心指标</h2>
      <div class="metrics-container">
        <MetricCard
          title="总资产"
          :value="formatNumber(overview.assetStatistics.totalAssets)"
          :trend="overview.assetStatistics.newAssets"
          trendLabel="本月新增"
          :growthRate="overview.assetStatistics.growthRate"
          icon="el-icon-box"
          type="primary"
        />
        <MetricCard
          title="风险分布"
          :highRisk="overview.riskStatistics.highRisk"
          :mediumRisk="overview.riskStatistics.mediumRisk"
          :lowRisk="overview.riskStatistics.lowRisk"
          icon="el-icon-warning"
          type="warning"
        />
        <MetricCard
          title="处理效率"
          :processingRate="overview.processingStatistics.processingRate"
          :avgTime="overview.processingStatistics.avgTime"
          :onTimeRate="overview.processingStatistics.onTimeRate"
          icon="el-icon-clock"
          type="success"
        />
      </div>
    </el-card>

    <!-- 图表区域 -->
    <el-card class="charts-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">图表分析</h2>
      <div class="charts-container">
        <div class="chart-item">
          <h3 class="chart-title">资产趋势图</h3>
          <div class="chart-wrapper">
            <el-loading v-if="chartLoading.assetTrend" fullscreen="false" />
            <div ref="assetTrendChart" class="chart" />
          </div>
        </div>
        <div class="chart-item">
          <h3 class="chart-title">风险等级分布</h3>
          <div class="chart-wrapper">
            <el-loading
              v-if="chartLoading.riskDistribution"
              fullscreen="false"
            />
            <div ref="riskDistributionChart" class="chart" />
          </div>
        </div>
        <div class="chart-item">
          <h3 class="chart-title">部门处理对比</h3>
          <div class="chart-wrapper">
            <el-loading
              v-if="chartLoading.departmentComparison"
              fullscreen="false"
            />
            <div ref="departmentComparisonChart" class="chart" />
          </div>
        </div>
        <div class="chart-item">
          <h3 class="chart-title">任务执行统计</h3>
          <div class="chart-wrapper">
            <el-loading v-if="chartLoading.taskExecution" fullscreen="false" />
            <div ref="taskExecutionChart" class="chart" />
          </div>
        </div>
        <div class="chart-item">
          <h3 class="chart-title">场景使用频率</h3>
          <div class="chart-wrapper">
            <el-loading v-if="chartLoading.sceneFrequency" fullscreen="false" />
            <div ref="sceneFrequencyChart" class="chart" />
          </div>
        </div>
        <div class="chart-item">
          <h3 class="chart-title">责任人绩效</h3>
          <div class="chart-wrapper">
            <el-loading
              v-if="chartLoading.personPerformance"
              fullscreen="false"
            />
            <div ref="personPerformanceChart" class="chart" />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 详细报表区域 -->
    <el-card class="detail-report-card" :body-style="{ padding: '15px' }">
      <h2 class="section-title">详细报表</h2>
      <DetailReportTable
        :time-range="timeRange"
        :date-range="dateRange"
        @tab-change="handleReportTabChange"
      />
    </el-card>

    <!-- 导出报表弹窗 -->
    <ExportReportDialog
      v-model="exportDialogVisible"
      :current-report-type="activeReportTab"
      :time-range="timeRange"
      :date-range="dateRange"
      :department-options="props.departmentOptions"
      @export-success="handleExportSuccess"
    />

    <!-- 数据对比弹窗 -->
    <el-dialog v-model="comparisonDialogVisible" title="数据对比" :width="600">
      <el-form :model="comparisonForm" label-width="100px">
        <el-form-item label="对比类型" prop="comparisonType">
          <el-select
            v-model="comparisonForm.comparisonType"
            placeholder="请选择对比类型"
          >
            <el-option label="部门对比" value="department" />
            <el-option label="时间周期对比" value="time_period" />
            <el-option label="风险等级对比" value="risk_level" />
          </el-select>
        </el-form-item>
        <el-form-item label="对比项目" prop="items">
          <el-select
            v-model="comparisonForm.items"
            placeholder="请选择对比项目"
            multiple
            v-if="comparisonForm.comparisonType === 'department'"
          >
            <el-option
              v-for="dept in departments"
              :key="dept.id"
              :label="dept.name"
              :value="dept.name"
            />
          </el-select>
          <el-select
            v-model="comparisonForm.items"
            placeholder="请选择对比周期"
            multiple
            v-if="comparisonForm.comparisonType === 'time_period'"
          >
            <el-option label="本月" value="current_month" />
            <el-option label="上月" value="last_month" />
            <el-option label="本季度" value="current_quarter" />
            <el-option label="上季度" value="last_quarter" />
          </el-select>
          <el-select
            v-model="comparisonForm.items"
            placeholder="请选择风险等级"
            multiple
            v-if="comparisonForm.comparisonType === 'risk_level'"
          >
            <el-option label="高危" value="high" />
            <el-option label="中危" value="medium" />
            <el-option label="低危" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="对比指标" prop="metrics">
          <el-select
            v-model="comparisonForm.metrics"
            placeholder="请选择对比指标"
            multiple
          >
            <el-option label="资产数量" value="asset_count" />
            <el-option label="处理率" value="processing_rate" />
            <el-option label="平均处理时间" value="avg_processing_time" />
            <el-option label="风险占比" value="risk_percentage" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="comparisonDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmComparison"
          >确认对比</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, nextTick, computed } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { Download, Refresh } from "@element-plus/icons-vue";
import * as echarts from "echarts";
import type { ECharts } from "echarts";
import MetricCard from "./components/MetricCard.vue";
import DetailReportTable from "./components/DetailReportTable.vue";
import ExportReportDialog from "./components/ExportReportDialog.vue";
import {
  getReportOverview,
  getTrendData,
  getDistributionData,
  getComparisonData,
} from "../../servers";
import { riskLevelList } from "../../helps";

// 定义props
const props = defineProps<{
  task?: string;
  departmentOptions?: Array<{ label: string; value: string }>;
}>();

// 页面状态
const timeRange = ref("month");
const dateRange = ref<[Date, Date] | null>(null);
const activeReportTab = ref("asset");
const chartLoading = reactive({
  assetTrend: false,
  riskDistribution: false,
  departmentComparison: false,
  taskExecution: false,
  sceneFrequency: false,
  personPerformance: false,
});

// 弹窗状态
const exportDialogVisible = ref(false);
const comparisonDialogVisible = ref(false);

// 对比表单
const comparisonForm = reactive({
  comparisonType: "department",
  items: [] as any[],
  metrics: ["asset_count", "processing_rate"],
});

// 部门数据（从props获取）
const departments = computed(() => {
  return (props.departmentOptions || []).map((dept) => ({
    id: dept.value,
    name: dept.label,
  }));
});

// 概览数据
const overview = reactive({
  assetStatistics: {
    totalAssets: 2456,
    newAssets: 156,
    growthRate: 12.3,
  },
  riskStatistics: {
    highRisk: 291,
    mediumRisk: 487,
    lowRisk: 1156,
  },
  processingStatistics: {
    processingRate: 78.5,
    avgTime: 2.8,
    onTimeRate: 92.1,
  },
});

// 图表实例
const assetTrendChart = ref<HTMLElement | null>(null);
const riskDistributionChart = ref<HTMLElement | null>(null);
const departmentComparisonChart = ref<HTMLElement | null>(null);
const taskExecutionChart = ref<HTMLElement | null>(null);
const sceneFrequencyChart = ref<HTMLElement | null>(null);
const personPerformanceChart = ref<HTMLElement | null>(null);

// 格式化数字（添加千位分隔符）
const formatNumber = (num: number) => {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
};

// 时间范围变更
const handleTimeRangeChange = () => {
  if (timeRange.value !== "custom") {
    refreshData();
  }
};

// 刷新数据
const refreshData = async () => {
  // const loading = ElLoading.service({ text: "正在刷新数据..." });

  try {
    // 构建查询参数
    const params: any = {
      time_range: timeRange.value === "custom" ? "custom" : timeRange.value,
    };

    if (timeRange.value === "custom" && dateRange.value) {
      params.start_date = formatDate(dateRange.value[0]);
      params.end_date = formatDate(dateRange.value[1]);
    }

    // 获取概览数据
    const overviewResult = await getReportOverview(params);
    Object.assign(overview, overviewResult.data);

    // 刷新图表数据
    await refreshAllCharts(params);
  } catch (error: any) {
    ElMessage.error(error?.message || "数据刷新失败");
  } finally {
    //
  }
};

// 刷新所有图表
const refreshAllCharts = async (params: any) => {
  await Promise.all([
    renderAssetTrendChart(params),
    renderRiskDistributionChart(params),
    renderDepartmentComparisonChart(params),
    renderTaskExecutionChart(params),
    renderSceneFrequencyChart(params),
    renderPersonPerformanceChart(params),
  ]);
};

// 渲染资产趋势图
const renderAssetTrendChart = async (params: any) => {
  chartLoading.assetTrend = true;
  try {
    const result = await getTrendData({
      ...params,
      metrics: "assets",
      interval: "day",
    });

    if (
      !result.data ||
      !result.data.trends ||
      result.data.trends.length === 0
    ) {
      chartLoading.assetTrend = false;
      return;
    }

    const trends = result.data.trends || [];
    const chartInstance = echarts.init(assetTrendChart.value as HTMLElement);

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
        },
        formatter: (params: any) => {
          const item = params[0];
          const data = item.data;
          return `
            <div style="padding: 5px;">
              <div><strong>${item.axisValue}</strong></div>
              <div>总资产: ${data.total_assets || 0}</div>
              <div>高风险资产: ${data.high_risk_assets || 0}</div>
              <div>极高风险资产: ${data.critical_assets || 0}</div>
              <div>平均风险分: ${data.avg_risk_score || 0}</div>
            </div>
          `;
        },
      },
      legend: {
        data: ["总资产", "高风险资产", "极高风险资产"],
        top: 10,
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        top: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: trends.map((item: any) => item.date),
        axisLabel: {
          rotate: 45,
        },
      },
      yAxis: [
        {
          type: "value",
          name: "资产数量",
          position: "left",
        },
        {
          type: "value",
          name: "风险分",
          position: "right",
          max: 100,
        },
      ],
      series: [
        {
          name: "总资产",
          type: "line",
          data: trends.map((item: any) => item.total_assets || 0),
          smooth: true,
          lineStyle: {
            width: 3,
            color: "#409EFF",
          },
          itemStyle: {
            color: "#409EFF",
          },
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ],
            },
          },
        },
        {
          name: "高风险资产",
          type: "line",
          data: trends.map((item: any) => item.high_risk_assets || 0),
          smooth: true,
          lineStyle: {
            width: 2,
            color: "#FAAD14",
          },
          itemStyle: {
            color: "#FAAD14",
          },
        },
        {
          name: "极高风险资产",
          type: "line",
          data: trends.map((item: any) => item.critical_assets || 0),
          smooth: true,
          lineStyle: {
            width: 2,
            color: "#F5222D",
          },
          itemStyle: {
            color: "#F5222D",
          },
        },
        {
          name: "平均风险分",
          type: "line",
          yAxisIndex: 1,
          data: trends.map((item: any) => item.avg_risk_score || 0),
          smooth: true,
          lineStyle: {
            width: 2,
            type: "dashed",
            color: "#722ED1",
          },
          itemStyle: {
            color: "#722ED1",
          },
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    const resizeHandler = () => {
      chartInstance.resize();
    };
    window.addEventListener("resize", resizeHandler);

    // 清理函数
    return () => {
      window.removeEventListener("resize", resizeHandler);
    };
  } catch (error) {
    console.error("资产趋势图渲染失败:", error);
    ElMessage.error("资产趋势图加载失败");
  } finally {
    chartLoading.assetTrend = false;
  }
};

// 渲染风险等级分布图
const renderRiskDistributionChart = async (params: any) => {
  chartLoading.riskDistribution = true;
  try {
    const result = await getDistributionData({
      ...params,
      dimension: "risk_level",
    });
    const chartInstance = echarts.init(
      riskDistributionChart.value as HTMLElement
    );

    const option = {
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: 10,
        formatter: (name: string) => {
          const riskLevelName = riskLevelList.find(
            (d: any) => d.label === name
          )?.value;
          const item = result.data.distribution.find(
            (d: any) => d.name === riskLevelName
          );
          return `${name} (${item?.value || 0})`;
        },
      },
      series: [
        {
          name: "风险等级",
          type: "pie",
          radius: ["40%", "70%"],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: "#fff",
            borderWidth: 2,
          },
          label: {
            show: false,
            position: "center",
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: "bold",
              formatter: "{b}: {d}%",
            },
          },
          labelLine: {
            show: false,
          },
          data: result.data.distribution.map((item: any) => ({
            value: item.value,
            name:
              riskLevelList.find((d) => d.value === item.name)?.label ||
              item.name,
            itemStyle: {
              color: item.color,
            },
          })),
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", () => {
      chartInstance.resize();
    });
  } catch (error) {
    console.error("风险等级分布图渲染失败:", error);
  } finally {
    chartLoading.riskDistribution = false;
  }
};

// 渲染部门处理对比图
const renderDepartmentComparisonChart = async (params: any) => {
  chartLoading.departmentComparison = true;
  try {
    const result = await getDistributionData({
      ...params,
      dimension: "department",
    });

    const chartInstance = echarts.init(
      departmentComparisonChart.value as HTMLElement
    );

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
      },
      legend: {
        data: ["处理率(%)", "平均处理时间(天)"],
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: result.data.distribution.map((item: any) => item.name),
      },
      yAxis: [
        {
          type: "value",
          name: "处理率(%)",
          max: 100,
        },
        {
          type: "value",
          name: "平均处理时间(天)",
          position: "right",
        },
      ],
      series: [
        {
          name: "处理率(%)",
          type: "bar",
          data: result.data.distribution.map((item: any) => item.percentage),
          itemStyle: {
            color: "#52C41A",
          },
        },
        {
          name: "平均处理时间(天)",
          type: "line",
          yAxisIndex: 1,
          data: result.data.distribution.map(
            (item: any) => item.high_risk_count
          ),
          lineStyle: {
            color: "#409EFF",
          },
          itemStyle: {
            color: "#409EFF",
          },
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", () => {
      chartInstance.resize();
    });
  } catch (error) {
    console.error("部门处理对比图渲染失败:", error);
  } finally {
    chartLoading.departmentComparison = false;
  }
};

// 渲染任务执行统计图表
const renderTaskExecutionChart = async (params: any) => {
  chartLoading.taskExecution = true;
  try {
    const result = await getTrendData({
      ...params,
      metrics: "processing",
      interval: "day",
    });

    if (
      !result.data ||
      !result.data.trends ||
      result.data.trends.length === 0
    ) {
      chartLoading.taskExecution = false;
      return;
    }

    const trends = result.data.trends || [];
    const chartInstance = echarts.init(taskExecutionChart.value as HTMLElement);

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "cross",
        },
      },
      legend: {
        data: ["总资产", "高风险资产"],
        top: 10,
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        top: "15%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: trends.map((item: any) => item.date),
        axisLabel: {
          rotate: 45,
        },
      },
      yAxis: {
        type: "value",
        name: "任务数量",
      },
      series: [
        {
          name: "总资产",
          type: "line",
          stack: "总量",
          data: trends.map((item: any) => item.total_assets || 0),
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(64, 158, 255, 0.3)" },
                { offset: 1, color: "rgba(64, 158, 255, 0.1)" },
              ],
            },
          },
          lineStyle: {
            color: "#409EFF",
          },
          itemStyle: {
            color: "#409EFF",
          },
        },
        {
          name: "高风险资产",
          type: "line",
          stack: "总量",
          data: trends.map((item: any) => item.high_risk_assets || 0),
          areaStyle: {
            color: {
              type: "linear",
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [
                { offset: 0, color: "rgba(250, 173, 20, 0.3)" },
                { offset: 1, color: "rgba(250, 173, 20, 0.1)" },
              ],
            },
          },
          lineStyle: {
            color: "#FAAD14",
          },
          itemStyle: {
            color: "#FAAD14",
          },
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    const resizeHandler = () => {
      chartInstance.resize();
    };
    window.addEventListener("resize", resizeHandler);

    // 清理函数
    return () => {
      window.removeEventListener("resize", resizeHandler);
    };
  } catch (error) {
    console.error("任务执行统计图表渲染失败:", error);
    ElMessage.error("任务执行统计图表加载失败");
  } finally {
    chartLoading.taskExecution = false;
  }
};

// 渲染场景使用频率图表
const renderSceneFrequencyChart = async (params: any) => {
  chartLoading.sceneFrequency = true;
  try {
    const result = await getDistributionData({
      ...params,
      dimension: "scene",
      top_n: 10,
    });

    if (
      !result.data ||
      !result.data.distribution ||
      result.data.distribution.length === 0
    ) {
      chartLoading.sceneFrequency = false;
      return;
    }

    const distribution = result.data.distribution || [];
    // 按value降序排序
    const sortedData = [...distribution].sort(
      (a: any, b: any) => b.value - a.value
    );

    const chartInstance = echarts.init(
      sceneFrequencyChart.value as HTMLElement
    );

    const option = {
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: (params: any) => {
          const item = params[0];
          const data = sortedData[item.dataIndex];
          return `
            <div style="padding: 5px;">
              <div><strong>${item.name}</strong></div>
              <div>数量: ${data.value || 0}</div>
              <div>占比: ${data.percentage?.toFixed(2) || 0}%</div>
              ${
                data.high_risk_count
                  ? `<div>高风险: ${data.high_risk_count}</div>`
                  : ""
              }
            </div>
          `;
        },
      },
      grid: {
        left: "15%",
        right: "4%",
        bottom: "3%",
        top: "5%",
        containLabel: false,
      },
      xAxis: {
        type: "value",
        name: "数量",
        axisLabel: {
          formatter: "{value}",
        },
      },
      yAxis: {
        type: "category",
        data: sortedData.map((item: any) => item.name || "未知"),
        inverse: true,
        axisLabel: {
          interval: 0,
          formatter: (value: string) => {
            if (value.length > 8) {
              return value.substring(0, 8) + "...";
            }
            return value;
          },
        },
      },
      series: [
        {
          name: "使用频率",
          type: "bar",
          data: sortedData.map((item: any) => ({
            value: item.value || 0,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: "#409EFF" },
                { offset: 1, color: "#69b1ff" },
              ]),
            },
          })),
          label: {
            show: true,
            position: "right",
            formatter: (params: any) => {
              const data = sortedData[params.dataIndex];
              return `${data.value} (${data.percentage?.toFixed(1) || 0}%)`;
            },
          },
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    const resizeHandler = () => {
      chartInstance.resize();
    };
    window.addEventListener("resize", resizeHandler);

    // 清理函数
    return () => {
      window.removeEventListener("resize", resizeHandler);
    };
  } catch (error) {
    console.error("场景使用频率图表渲染失败:", error);
    ElMessage.error("场景使用频率图表加载失败");
  } finally {
    chartLoading.sceneFrequency = false;
  }
};

// 渲染责任人绩效图表
const renderPersonPerformanceChart = async (params: any) => {
  chartLoading.personPerformance = true;
  try {
    const result = await getComparisonData({
      ...params,
      comparison_type: "responsible_person",
    });

    const chartInstance = echarts.init(
      personPerformanceChart.value as HTMLElement
    );

    const option = {
      tooltip: {
        trigger: "item",
      },
      radar: {
        indicator: [
          { name: "处理率", max: 100 },
          { name: "准时率", max: 100 },
          { name: "准确率", max: 100 },
          { name: "响应速度", max: 100 },
          { name: "完成质量", max: 100 },
        ],
      },
      series: [
        {
          name: "责任人绩效",
          type: "radar",
          data: result.data.data.map((item: any) => {
            // 转换字符串为数字
            const confirmed = Number(item.confirmed) || 0;
            const total = Number(item.total) || 0;
            const pending = Number(item.pending) || 0;
            const falsePositive = Number(item.false_positive) || 0;
            const confirmRate = Number(item.confirm_rate) || 0;

            // 计算各项指标
            // 处理率：已确认数量 / 总数量 * 100
            const processingRate = total > 0 ? (confirmed / total) * 100 : 0;

            // 准时率：数据中没有，暂时用处理进度代替（已处理/总数）
            const onTimeRate =
              total > 0 ? ((total - pending) / total) * 100 : 0;

            // 准确率：已确认且非误报 / 已确认数量 * 100
            const accuracy =
              confirmed > 0
                ? ((confirmed - falsePositive) / confirmed) * 100
                : 0;

            // 响应速度：数据中没有，暂时用确认率代替（确认率越高，响应越快）
            const responseSpeed =
              confirmRate > 0 ? Math.min(confirmRate * 10, 100) : 0;

            // 完成质量：使用确认率，如果确认率是百分比形式（如2.11%），需要转换为0-100的评分
            // 假设 confirm_rate 是百分比数值，直接使用，如果超过100则限制为100
            const qualityScore = Math.min(confirmRate * 10, 100);

            return {
            value: [
                processingRate,
                onTimeRate,
                accuracy,
                responseSpeed,
                qualityScore,
            ],
            name: item.name,
            };
          }),
        },
      ],
    };

    chartInstance.setOption(option);

    // 监听窗口大小变化，重绘图表
    window.addEventListener("resize", () => {
      chartInstance.resize();
    });
  } catch (error) {
    console.error("责任人绩效图表渲染失败:", error);
  } finally {
    chartLoading.personPerformance = false;
  }
};

// 报表标签页切换
const handleReportTabChange = (tabName: string) => {
  activeReportTab.value = tabName;
};

// 导出报表
const handleExportReport = () => {
  exportDialogVisible.value = true;
};

// 导出成功回调
const handleExportSuccess = () => {
  // 可以在这里添加导出成功后的处理逻辑，比如刷新数据等
  console.log("报表导出成功");
};

// 切换对比弹窗
const toggleComparison = () => {
  comparisonDialogVisible.value = true;
};

// 确认对比
const confirmComparison = async () => {
  if (!comparisonForm.items || comparisonForm.items.length < 2) {
    ElMessage.warning("请至少选择两个对比项目");
    return;
  }

  try {
    const loading = ElLoading.service({ text: "正在生成对比数据..." });

    const params: any = {
      comparison_type: comparisonForm.comparisonType,
      items: Array.isArray(comparisonForm.items)
        ? comparisonForm.items.join(",")
        : comparisonForm.items,
      metrics: Array.isArray(comparisonForm.metrics)
        ? comparisonForm.metrics.join(",")
        : comparisonForm.metrics,
      time_range: timeRange.value === "custom" ? "custom" : timeRange.value,
    };

    if (timeRange.value === "custom" && dateRange.value) {
      params.start_date = formatDate(dateRange.value[0]);
      params.end_date = formatDate(dateRange.value[1]);
    }

    const result = await getComparisonData(params);

    // 简单处理：刷新图表以显示对比数据
    refreshAllCharts(params);

    ElMessage.success("对比数据生成成功");
    comparisonDialogVisible.value = false;
  } catch (error: any) {
    ElMessage.error(error?.message || "生成对比数据失败");
  }
};

// 格式化日期
const formatDate = (date: Date) => {
  return `${date.getFullYear()}-${(date.getMonth() + 1)
    .toString()
    .padStart(2, "0")}-${date.getDate().toString().padStart(2, "0")}`;
};

// 页面加载时初始化
onMounted(async () => {
  // 等待DOM渲染完成
  await nextTick();

  // 初始化图表
  if (assetTrendChart.value) {
    await refreshData();
  }
});

// 监听窗口大小变化，重绘所有图表
watch(
  () => window.innerWidth,
  () => {
    if (assetTrendChart.value) {
      echarts.getInstanceByDom(assetTrendChart.value)?.resize();
    }
    if (riskDistributionChart.value) {
      echarts.getInstanceByDom(riskDistributionChart.value)?.resize();
    }
    if (departmentComparisonChart.value) {
      echarts.getInstanceByDom(departmentComparisonChart.value)?.resize();
    }
    if (taskExecutionChart.value) {
      echarts.getInstanceByDom(taskExecutionChart.value)?.resize();
    }
    if (sceneFrequencyChart.value) {
      echarts.getInstanceByDom(sceneFrequencyChart.value)?.resize();
    }
    if (personPerformanceChart.value) {
      echarts.getInstanceByDom(personPerformanceChart.value)?.resize();
    }
  }
);
</script>

<style scoped lang="scss">
.pan-statistics-report {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: 600;
      margin: 0;
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .filter-card,
  .metrics-card,
  .charts-card,
  .detail-report-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: 1px solid #f0f0f0;
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin: 0 0 15px 0;
    color: #444;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .filter-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 15px;

    .filter-item {
      display: flex;
      align-items: center;
      gap: 8px;

      .filter-label {
        color: #666;
        white-space: nowrap;
      }
    }

    .filter-actions {
      margin-left: auto;
      display: flex;
      gap: 10px;
    }
  }

  .metrics-container {
    display: flex;
    gap: 15px;
    flex-wrap: wrap;
  }

  .charts-container {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }

  .chart-item {
    background-color: #fff;
    border-radius: 6px;
    padding: 15px;
    // box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
    border: 1px solid #f0f0f0;

    .chart-title {
      font-size: 14px;
      font-weight: 500;
      margin: 0 0 10px 0;
      color: #666;
    }

    .chart-wrapper {
      position: relative;
      height: 360px;
    }

    .chart {
      width: 36vw;
      height: 360px;
    }
  }

  .report-tabs {
    margin-bottom: 15px;
  }

  .report-content {
    position: relative;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  // 响应式调整
  @media (max-width: 1200px) {
    .charts-container {
      grid-template-columns: repeat(2, 1fr);
    }
  }

  @media (max-width: 768px) {
    .charts-container {
      grid-template-columns: 1fr;
    }

    .filter-container {
      flex-direction: column;
      align-items: flex-start;

      .filter-actions {
        margin-left: 0;
        width: 100%;
        justify-content: flex-end;
      }
    }
  }
}
</style>
